package com.baitai.common.utils;

import com.baitai.common.constant.Constants;
import com.baitai.common.utils.file.FileUploadUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {

    public static String generatorQRCode(String txt, String QRPath,String fileName,String baseDir,String endpoint,String accessKeyId,String accessKeySecret,String filedir,String bucketName) {
        try {
            // 设置二维码的宽度和高度
            int width = 300;
            int height = 300;

            // 设置编码的字符集
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());

            // 使用ZXing的MultiFormatWriter生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);

            // 将二维码保存到文件
            String filePath = QRPath+fileName; // 替换为你的文件路径
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(filePath));
            System.out.println("二维码已保存到: " + filePath);
            FileUploadUtils.getPathFileName(QRPath,fileName.substring(1,fileName.length()));
            File Qr = new File(filePath);
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.init(endpoint,accessKeyId,accessKeySecret,filedir,bucketName);
            InputStream inputStream = new FileInputStream(Qr);
            fileName = ossClientUtil.uploadImg2Oss(inputStream,baseDir+fileName);
            Qr.delete();
            return getOssPathFileName(baseDir, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return QRPath;
    }

    public static final String getOssPathFileName(String uploadDir, String fileName) throws IOException
    {
        return Constants.RESOURCE_PREFIX +  fileName;
    }
}
